<template>
  <editor :id="tinymceId" v-model="tinymceHtml" :init="init" :disabled="disabled"></editor>
</template>

<script setup lang="ts">
  import tinymce from 'tinymce/tinymce';
  import Editor from '@tinymce/tinymce-vue'; // 引入组件
  import 'tinymce/themes/silver';
  import 'tinymce/themes/silver/theme';
  import 'tinymce/icons/default'; //引入编辑器图标icon，不引入则不显示对应图标
  import 'tinymce/models/dom'; // 特别注意 tinymce 6.0.0 版本之后必须引入，否则不显示 这里是个坑 一定要引入
  // 都是富文本插件
  import 'tinymce/plugins/image';
  import 'tinymce/plugins/media';
  import 'tinymce/plugins/table';
  import 'tinymce/plugins/lists';
  import 'tinymce/plugins/wordcount';
  import 'tinymce/plugins/code';
  import 'tinymce/plugins/fullscreen';
  import 'tinymce/plugins/link';
  import 'tinymce/plugins/template';
  import 'tinymce/plugins/preview';
  import 'tinymce/plugins/advlist';
  import 'tinymce/plugins/autolink';

  import { uploadFile } from '@/api/common';
  import { basePublicURL, publicPathUrl } from '@/utils/common';
  import { useModel } from '@/hooks';
  const emits = defineEmits(['update:value']);
  const props = defineProps({
    placeholder: {
      type: String,
      default: () => {
        return '请输入内容';
      },
    },
    value: {
      type: String,
      default: () => {
        return '';
      },
    },
    editorHeight: {
      type: Number,
      default: 400,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default:
        'advlist autolink lists link lists image code table wordcount media fullscreen preview',
    }, // 必填
    toolbar: {
      type: [String, Array],
      default:
        'fontsize bold italic underline strikethrough forecolor blockquote backcolor code image preview | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link table | removeformat ',
    }, // 必填
  });
  const tinymceHtml = useModel(props, emits);
  const tinymceId = ref(`vue-tinymce-${+new Date()}${(Math.random() * 1000).toFixed(0)}`);
  const init = {
    convert_urls: false, // 是否转换url
    selector: `#${tinymceId.value}`, // 富文本编辑器的id,
    language_url: `${basePublicURL}tinymce/langs/zh-Hans.js`, // 引入语言包
    language: 'zh-Hans', // 设置语言
    theme: 'silver', // 主题
    skin_url: `${basePublicURL}tinymce/skins/ui/oxide`, // 引入样式
    height: props.editorHeight, // 这里的数据是在props里面就定义好了的
    branding: false, // 是否禁用“Powered by TinyMCE”
    menubar: false, // 顶部菜单栏显示
    plugins: props.plugins, // 这里的数据是在props里面就定义好了的
    toolbar: props.toolbar, // 这里的数据是在props里面就定义好了的
    placeholder: props.placeholder, // 这里的数据是在props里面就定义好了的
    font_family_formats:
      "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
    fontsize_formats: '11px 12px 14px 16px 18px 24px 36px 48px 64px 72px', //文字大小
    paste_merge_formats: true,
    toolbar_sticky: false,
    nonbreaking_force_tab: false,
    promotion: false,
    resize: false,
    paste_auto_cleanup_on_paste: false,
    file_picker_types: 'file',
    content_style: 'p {margin: 0; border: 0; padding: 0;} span {margin: 0; border: 0; padding: 0}',
    content_css: `${basePublicURL}tinymce/skins/content/default/content.css`, //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
    init_instance_callback: (editor) => {},
    // 图片本地上传方法  点击上传后执行的事件
    images_upload_handler: (blobInfo, progress) =>
      // eslint-disable-next-line no-async-promise-executor
      new Promise(async (resolve, reject) => {
        // 判断是否是图片类型
        if (!/image\/\w+/.test(blobInfo.blob().type)) {
          reject({ message: '上传图片格式不对' });
          return;
        }
        // 判断图片大小不能大于20MB
        if (blobInfo.blob().size > 20 * 1024 * 1024) {
          reject({ message: '上传图片不能大于20MB' });
          return;
        }
        // 上传图片需要，FormData 格式的文件；
        const formDataUp = new FormData();
        // img  是接口需要的上传的属性名，一般属性名是 file
        formDataUp.append('file', blobInfo.blob());
        const res = await uploadFile(formDataUp);
        if (res?.data) {
          let url = res.data?.url;
          // 判断是否为http/https开头，如果不是则拼接上http/https
          if (url && (!/^http/.test(url) || !/^https/.test(url))) {
            url = publicPathUrl + url;
          }
          resolve(url);
        } else {
          reject({ message: res?.msg || '上传失败' });
        }
      }),
  };

  onMounted(() => {
    tinymce.init({}); // 初始化富文本
  });
</script>

<style scoped lang="less"></style>
